package com.ca.ridersclubapplication;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Toast;

import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.CaptchaRequester;
import com.ca.ridersclubapplication.request.LoginRequester;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.ImmersiveActivity;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ea.ui.core.basic.EAButton;
import com.ea.ui.core.basic.EAInput;
import com.ea.ui.core.basic.EALink;
import com.ea.ui.core.util.Type;

import java.util.Objects;

public class ForgetActivity extends ImmersiveActivity {

    //  输入框相关
    private EAInput emailInput;
    private EAInput passwordInput;
    private EAInput codeInput;

    //  连接相关
    private EALink emailErrorLink;
    private EALink passwordErrorLink;
    private EALink codeErrorLink;

    //  按钮相关
    private EAButton backButton;
    private EAButton codeButton;
    private EAButton submitButton;
    private int btnType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);

        //  初始化
        init();

        //  设置动画
        setViewTransition();
    }

    /**
     * 初始化：视图、Retrofit服务接口，并对视图进行设置
     */
    private void init() {

        //  输入框相关
        emailInput = findViewById(R.id.ipt_email);
        passwordInput = findViewById(R.id.ipt_password);
        codeInput = findViewById(R.id.ipt_code);

        //  连接相关
        emailErrorLink = findViewById(R.id.link_error_email);
        passwordErrorLink = findViewById(R.id.link_error_password);
        codeErrorLink = findViewById(R.id.link_error_code);

        //  按钮相关
        backButton = findViewById(R.id.btn_back);
        codeButton = findViewById(R.id.btn_code);
        submitButton = findViewById(R.id.btn_submit);

        //  设置按钮
        setBackButton();
        setCodeButton();
        setSubmitButton();

        //  设置输入框
        setEmailInput();
        setPasswordInput();
        setCodeInput();
    }


    /**
     * 设置动画
     */
    private void setViewTransition() {

        backButton.setTransitionName("link:forget");
        emailInput.setTransitionName("input:email");
        passwordInput.setTransitionName("input:password");
        submitButton.setTransitionName("button:login");
    }


    /**
     * 设置返回按钮
     * 实现：
     *      1、点击按钮返回登录页面
     */
    private void setBackButton() {
        backButton.setOnClickListener(view -> {
            finishAfterTransition();
        });
    }


    /**
     * 设置 email 输入框
     * 实现：
     *      1、输入邮箱自动请求，校验账号是否存在
     *      2、email输入框、nickname输入框、password输入框 和 code输入框 同时通过校验时，开启注册按钮点击
     */
    private void setEmailInput() {

        emailInput.requestFocus();

        emailInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    //  email输入框 和 code输入框 内容检查，设置按钮是否可用
                    checkAllInput();

                    //  设置 code 按钮是否可用
                    boolean flag = emailInput.isVerify() && emailErrorLink.getText().toString().isEmpty();
                    codeButton.setDisable(!flag);

                    if (emailInput.isVerify()) {

                        String email = Objects.requireNonNull(emailInput.getText()).toString();

                        //  查询账号是否存在
                        AccountRequester.getIdByEmail(ForgetActivity.this, email, new AfterExecutor<Long>() {
                            @Override
                            public void execute(Result<Long> result) {
                                if (!result.isSuccess()) {
                                    //  如果账号不存在，则提示用户
                                    emailInput.setType(Type.DANGER);
                                    if (emailErrorLink.getVisibility() == View.GONE) {
                                    }
                                    emailErrorLink.setText(result.getMessage());
                                }
                                else {
                                    emailErrorLink.setText("");
                                }
                            }
                        });
                    }
                    else {
                        emailErrorLink.setText(R.string.tip_input_email);
                    }

                    checkAllInput();
                    //  设置 code 按钮是否可用
                    flag = emailInput.isVerify() && emailErrorLink.getText().toString().isEmpty();
                    codeButton.setDisable(!flag);
                }
                else {
                    emailErrorLink.setText("");
                }
            }
        });

        //  判断是否有 email 传入
        String email = getIntent().getStringExtra("email");
        if (email != null && !email.isEmpty()) {
            emailInput.setText(email);
        }
    }


    /**
     * 设置 password 输入框
     * 实现：
     *      1、输入内容时，显示校验失败提示
     *      2、email输入框 和 password输入框 同时通过校验时，开启登录按钮点击
     */
    private void setPasswordInput() {

        passwordInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    checkAllInput();

                    if (!passwordInput.verify()) {
                        passwordErrorLink.setText(R.string.tip_input_password);
                    }
                    else {
                        passwordErrorLink.setText("");
                    }

                    //  输入框 内容检查，设置按钮是否可用
                    checkAllInput();
                }
                else {
                    passwordErrorLink.setText("");
                }
            }
        });
    }


    /**
     * 设置 code 输入框
     * 实现：
     *      1、输入内容时，显示校验失败提示
     *      2、email输入框、nickname输入框、password输入框 和 code输入框 同时通过校验时，开启注册按钮点击
     */
    private void setCodeInput() {

        codeInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    //  输入框 内容检查，设置按钮是否可用
                    checkAllInput();

                    if (!codeInput.verify()) {
                        codeErrorLink.setText(R.string.tip_input_code);
                    }
                    else {
                        codeErrorLink.setText("");
                    }

                    checkAllInput();
                }
                else {
                    codeErrorLink.setText("");
                }
            }
        });
    }


    /**
     * 验证输入框内容
     */
    private void checkAllInput() {

        boolean flag = emailInput.isVerify() && codeInput.isVerify() && passwordInput.isVerify()
                && emailErrorLink.getText().toString().isEmpty()
                && codeErrorLink.getText().toString().isEmpty()
                && passwordErrorLink.getText().toString().isEmpty();

        if (flag) {
            submitButton.setType(Type.PRIMARY);
            submitButton.setDisable(false);
        }
        else {
            submitButton.setType(btnType);
            submitButton.setDisable(true);
        }
    }


    /**
     * 设置 code 按钮
     * 实现：
     *      1、点击发送获取验证码请求
     */
    private void setCodeButton() {
        codeButton.setOnClickListener(view -> {

            codeButton.setDisable(true);

            String email = Objects.requireNonNull(emailInput.getText()).toString();
            CaptchaRequester.sendCaptcha(this, email, "重置密码", new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {

                        //  发送验证码成功
                        Toast.makeText(ForgetActivity.this, "发送成功", Toast.LENGTH_SHORT).show();

                        //  开启 60s 倒计时
                        new CountDownTimer(60 * 1000, 1000) {

                            private final String codeBtnText = codeButton.getText().toString();
                            private int m = 60;

                            @Override
                            public void onTick(long millisUntilFinished) {
                                codeButton.setDisable(true);
                                String text = (m > 9 ? (m + "") : ("0" + m)) + "s后再试";
                                codeButton.setText(text);
                                m--;
                            }

                            @Override
                            public void onFinish() {
                                codeButton.setText(codeBtnText);
                                codeButton.setDisable(false);
                            }
                        }.start();
                    }
                    else {
                        Toast.makeText(ForgetActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        codeButton.setDisable(false);
                    }
                }
            });
        });
    }


    /**
     * 设置 注册 按钮
     * 实现：
     *      1、点击注册按钮发起注册请求
     */
    private void setSubmitButton() {

        //  缓存按钮原 type
        btnType = submitButton.getType();

        submitButton.setOnClickListener(v -> {

            submitButton.setDisable(true);

            if (!codeInput.verify()) {
                codeErrorLink.setText(R.string.tip_input_code);
            }

            if (emailInput.verify() && codeInput.verify()) {

                //  输入内容校验通过，发起登录请求
                String email = Objects.requireNonNull(emailInput.getText()).toString();
                String password = Objects.requireNonNull(passwordInput.getText()).toString();
                String code = Objects.requireNonNull(codeInput.getText()).toString();
                LoginRequester.updatePassword(this, null, email, code, password, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            //  更新成功
                            Toast.makeText(ForgetActivity.this, "密码更新成功", Toast.LENGTH_SHORT).show();
                            finishAfterTransition();
                        }
                        else {
                            Toast.makeText(ForgetActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }
}